<template>
  <input type="text" v-model="user.id">
  <input type="text" v-model="user.name">
  <button @click="addItem">提交</button>
  <ul>
    <li v-for="(item, i) in data.arr" :key="item.id" @click="removeItem(i)">{{ item.name }}</li>
  </ul>
</template>

<script>
import { reactive } from 'vue'
const useDelItem = () => {
  // !reactive 可以普通对象包装成响应式的对象
  const data = reactive({
    arr: [
      {
        id: 0,
        name: 'ifer',
      },
      {
        id: 1,
        name: 'elser',
      },
      {
        id: 2,
        name: 'xxx',
      },
    ],
  })

  const removeItem = (i) => {
    data.arr.splice(i, 1)
  }
  return {
    data,
    removeItem
  }
}

const useAddItem = (data) => {
  // !#1 收集数据用的，和 input 框双向绑定
  const user = reactive({
    id: '',
    name: ''
  })

  // !#2 添加 user 到 data.arr
  const addItem = () => {
    // 推荐写法
    data.arr.push({
      ...user
    })

    user.id = ''
    user.name = ''
    // data.arr.push(Object.assign({}, user))
  }
  return {
    user,
    addItem
  }
}
export default {
  setup() {
    const { data, removeItem } = useDelItem()
    const { user, addItem } = useAddItem(data)
    return { data, removeItem, user, addItem }
  }
}
</script>